package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Assert;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;

    public Boolean checkPhone(String phone) {
        return userInfoMapper.checkPhone(phone) == null;
    }

    public AjaxResult userRegist(String nickname, String password, String rpassword, String verifyCode, String phone) {
        AjaxResult result = new AjaxResult();
        try {
            //1.判断参数非空
            Assert.hasLength(nickname,"昵称不能为空");
            Assert.hasLength(password,"密码不能为空");
            Assert.hasLength(rpassword, "确认密码不能为空");
            Assert.hasLength(verifyCode, "验证码不能为空");
            Assert.hasLength(phone, "手机号不能为空");
            //2.判断两次密码是否一致
            Assert.equals(password, rpassword, "两次输入的密码不一致");
            //3.校验验证码
            String vc = verifyCodeCacheService.getVerifyCode(phone);
            Assert.equals(vc, verifyCode, "验证码不正确");

            //4.封装对象,保存默认数据
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            userInfo.setPassword(password);
            userInfo.setPhone(phone);
            //默认数据
            userInfo.setLevel(1);
            userInfo.setCity("广州");
            userInfo.setGender(UserInfo.GENDER_NONE);
            userInfo.setEmail("xxx@163.com");

            //5.保存到数据库
            userInfoMapper.insert(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    public AjaxResult userLogin(String phone, String password) {
        AjaxResult result = new AjaxResult();
        try {
            //1.参数的非空
            Assert.hasLength(phone,"手机号不能为空");
            Assert.hasLength(password,"密码不能为空");
            //2.用户信息数据库匹配校验
            UserInfo userInfo = userInfoMapper.selectByInfo(phone, password);
            //登录失败
            if (userInfo == null) {
                throw new RuntimeException("账号密码不匹配");
            }
            //登录成功
            result.addData(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }
}
